  import 'package:flutter/foundation.dart';
import 'local_config_manager.dart';
import 'server_config.dart';

/// 应用配置类 - 简化版本，直接从本地配置管理器读取
class AppConfig {
  static AppConfig? _instance;
  static AppConfig get instance => _instance ??= AppConfig._();
  
  // 🔑 静态getter，用于快速访问（用于AuthService等）
  static String get serverUrl => instance.baseUrl;
  
  AppConfig._();
  
  // 直接从本地配置管理器读取配置，使用 ServerConfig 作为默认值
  String get baseUrl => LocalConfigManager.instance.getValue<String>('baseUrl', ServerConfig.baseUrl)!;
  String get tcpTunnelHost => LocalConfigManager.instance.getValue<String>('tcpHost', ServerConfig.tcpHost)!;
  int get tcpTunnelPort => LocalConfigManager.instance.getValue<int>('tcpPort', ServerConfig.tcpPort)!;
  Duration get timeout => Duration(milliseconds: LocalConfigManager.instance.getValue<int>('timeout', ServerConfig.timeout)!);
  Duration get mockDelay => Duration(milliseconds: LocalConfigManager.instance.getValue<int>('mockDelay', ServerConfig.mockDelay)!);
  
  // 隧道配置
  String get defaultDomain => LocalConfigManager.instance.getValue<String>('defaultDomain', ServerConfig.defaultDomain)!;
  bool get autoReconnectEnabled => LocalConfigManager.instance.getValue<bool>('autoReconnect', ServerConfig.autoReconnect)!;
  
  // 协议映射（固定不变）
  Map<String, String> protocolMap = {
    'HTTP': 'http',
    'HTTPS': 'https',
    'SSH': 'ssh',
    'FTP': 'ftp',
    'MySQL': 'mysql',
    'PostgreSQL': 'postgresql',
    'Redis': 'redis',
    'MongoDB': 'mongodb',
  };
  
  // 初始化配置 - 简化版本，只需要初始化本地配置管理器
  Future<void> initialize() async {
    debugPrint('🔧 AppConfig: 开始初始化（使用本地配置管理器）');
    
    // 初始化本地配置管理器
    await LocalConfigManager.instance.initialize();
    
    debugPrint('✅ AppConfig: 初始化完成，当前配置:');
    debugPrint('   ├─ baseUrl: $baseUrl');
    debugPrint('   ├─ tcpTunnelHost: $tcpTunnelHost');
    debugPrint('   ├─ tcpTunnelPort: $tcpTunnelPort');
    debugPrint('   ├─ defaultDomain: $defaultDomain');
    debugPrint('   └─ autoReconnectEnabled: $autoReconnectEnabled');
  }
  
  /// 获取API URL
  String getApiUrl(String path) {
    // 确保路径以/开头
    if (!path.startsWith('/')) {
      path = '/$path';
    }
    return '$baseUrl$path';
  }
  
  /// 获取TCP隧道地址
  String getTcpTunnelAddress() {
    return '$tcpTunnelHost:$tcpTunnelPort';
  }
  
  /// 检查是否为开发环境
  bool get isDevelopment {
    return baseUrl.contains('localhost') || 
           baseUrl.contains('127.0.0.1') ||
           baseUrl.contains('192.168.') ||
           baseUrl.contains('10.0.');
  }
  
  /// 设置配置值（现在直接操作本地配置管理器）
  Future<bool> setBaseUrl(String url) async {
    debugPrint('🔧 AppConfig: 设置 baseUrl = $url');
    return await LocalConfigManager.instance.setValue('baseUrl', url);
  }
  
  Future<bool> setTcpTunnelHost(String host) async {
    debugPrint('🔧 AppConfig: 设置 tcpHost = $host');
    return await LocalConfigManager.instance.setValue('tcpHost', host);
  }
  
  Future<bool> setTcpTunnelPort(int port) async {
    debugPrint('🔧 AppConfig: 设置 tcpPort = $port');
    return await LocalConfigManager.instance.setValue('tcpPort', port);
  }
  
  Future<bool> setDefaultDomain(String domain) async {
    debugPrint('🔧 AppConfig: 设置 defaultDomain = $domain');
    return await LocalConfigManager.instance.setValue('defaultDomain', domain);
  }
  
  Future<bool> setAutoReconnectEnabled(bool enabled) async {
    debugPrint('🔧 AppConfig: 设置 autoReconnect = $enabled');
    return await LocalConfigManager.instance.setValue('autoReconnect', enabled);
  }
  
  /// 批量设置配置
  Future<bool> updateConfig({
    String? baseUrl,
    String? tcpHost,
    int? tcpPort,
    String? defaultDomain,
    bool? autoReconnect,
    int? timeout,
    int? mockDelay,
  }) async {
    final updates = <String, dynamic>{};
    
    if (baseUrl != null) updates['baseUrl'] = baseUrl;
    if (tcpHost != null) updates['tcpHost'] = tcpHost;
    if (tcpPort != null) updates['tcpPort'] = tcpPort;
    if (defaultDomain != null) updates['defaultDomain'] = defaultDomain;
    if (autoReconnect != null) updates['autoReconnect'] = autoReconnect;
    if (timeout != null) updates['timeout'] = timeout;
    if (mockDelay != null) updates['mockDelay'] = mockDelay;
    
    if (updates.isNotEmpty) {
      debugPrint('🔧 AppConfig: 批量更新配置，共 ${updates.length} 项');
      return await LocalConfigManager.instance.setValues(updates);
    }
    
    return true;
  }
  
  /// 重置为默认配置
  Future<bool> resetToDefault() async {
    debugPrint('🔄 AppConfig: 重置为默认配置');
    return await LocalConfigManager.instance.resetToDefault();
  }
  
  /// 获取调试信息
  String getDebugInfo() {
    final info = StringBuffer();
    info.writeln('=== AppConfig 配置信息 ===');
    info.writeln('baseUrl: $baseUrl');
    info.writeln('tcpTunnelHost: $tcpTunnelHost');
    info.writeln('tcpTunnelPort: $tcpTunnelPort');
    info.writeln('defaultDomain: $defaultDomain');
    info.writeln('autoReconnectEnabled: $autoReconnectEnabled');
    info.writeln('timeout: ${timeout.inMilliseconds}ms');
    info.writeln('mockDelay: ${mockDelay.inMilliseconds}ms');
    info.writeln('isDevelopment: $isDevelopment');
    info.writeln('\n${LocalConfigManager.instance.getDebugInfo()}');
    return info.toString();
  }
}